package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 李旭
 * @date 2021/10/26 11:38
 * @Description:
 *
 *   基于死信的 Java配置类
 */
@Configuration
public class DeadLetterMqConfig {


    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    //交换机
    @Bean
    public Exchange deadLetterExchange(){
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }
    //队列  TTL 存活时间
    @Bean
    public Queue deadLetterQueue(){
        Map<String, Object> arguments = new HashMap<>();
        //ttl   毫秒
        arguments.put("x-message-ttl",13*1000);  //队列的TTl
        // 过期转发的交换机
        arguments.put("x-dead-letter-exchange",exchange_dead);
        //过期转发的routingKey
        arguments.put("x-dead-letter-routing-key",routing_dead_2);

        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }
    //普通队列
    @Bean
    public Queue nQueue(){
        return QueueBuilder.durable(queue_dead_2).build();
    }
    //Binging   所有的队列 交换机 都在SpringIOC容器  可以从容器中获取
    @Bean
    public Binding bindingDeadLetterQueueToDeadLetterExchange(
                @Qualifier(value = "deadLetterQueue") Queue deadLetterQueue,
                @Qualifier(value = "deadLetterExchange") Exchange deadLetterExchange
                ){

        return BindingBuilder.bind(deadLetterQueue).to(deadLetterExchange).with(routing_dead_1).noargs();
    }
    @Bean
    public Binding bindingNQueueToDeadLetterExchange(
            @Qualifier(value = "nQueue") Queue nQueue,
            @Qualifier(value = "deadLetterExchange") Exchange deadLetterExchange
    ){
        return BindingBuilder.bind(nQueue).to(deadLetterExchange).with(routing_dead_2).noargs();
    }
}
